//
//  YZChatUtils.m
//  CocoaAsyncSocketClient
//
//  Created by lixiaoyi on 2018/7/5.
//  Copyright © 2018年 lixiaoyi. All rights reserved.
//

#import "YZChatUtils.h"

@implementation YZChatUtils

/**
 获取时间戳
 
 @return 返回10位的时间戳，13位的字符串(*1000主要是和别的系统语言一致)
 */

+ (NSString *)getTimeInterval{
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    //    NSTimeInterval interval = [date timeIntervalSince1970] * 1000;
    NSTimeInterval interval = [date timeIntervalSince1970];
    
    NSString *timeString = [NSString stringWithFormat:@"%.0f", interval];
    return timeString;
}

/**
 获取时间戳
 
 @return 返回13位时间戳
 */
+ (NSString *)getTimeInterval2 {
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval interval = [date timeIntervalSince1970] * 1000;
    
    NSString *timeString = [NSString stringWithFormat:@"%.0f", interval];
    return timeString;
}



/**
 时间戳转换成时间
 
 @param interval 时间戳
 @return 时间
 */
+ (NSString *)timeIntervalToTime:(NSString *)interval {
    NSTimeInterval timeInterval = [interval doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString       = [formatter stringFromDate: date];
    return dateString;
}

/**
 把一个日期时间转成聊天格式显示：
 消息大于1周，显示为“2018年7月8日 16:00”
 消息小于1周，大于昨天，显示为“周三 16:00”
 消息小于1周，昨天，显示为“昨天 16：00”
 消息是今天，显示：”16：00“
 
 @param timeStamp 时间戳
 @return 聊天格式显示的字符串
 */
+ (NSString *)showChatTime:(int64_t)timeStamp {
    NSString *chatTimeStr = @"";
    NSString *timeStampStr = [NSString stringWithFormat:@"%lld",timeStamp];
    // 如果是13位则转成10位
    if (timeStampStr.length == 13) {
        timeStamp = [[timeStampStr substringToIndex:10] doubleValue];
    }
    
    // 获取当前时间戳
    int64_t currStamp = [[self getTimeInterval] integerValue];
    
    NSDate *beDate = [NSDate dateWithTimeIntervalSince1970:timeStamp];
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"dd"];
    NSString *nowDay = [df stringFromDate:[NSDate date]];
    NSString *lastDay = [df stringFromDate:beDate];
    
    int64_t dValue = currStamp - timeStamp;
    if (dValue < 24 * 60 * 60 && [nowDay integerValue] == [lastDay integerValue] ) {
        // 今天
        chatTimeStr = [self showTimeFormat:@"HH:mm" interval:timeStamp];
    } else if (dValue < 2 * 24 * 60 * 60 &&  [nowDay integerValue] != [lastDay integerValue]) {
        // 昨天
        if ([nowDay integerValue] - [lastDay integerValue] == 1 || ([lastDay integerValue] - [nowDay integerValue] > 10 && [nowDay integerValue] == 1)) {
            chatTimeStr = [self showTimeFormat:@"昨天 HH:mm" interval:timeStamp];
        } else {
            [df setDateFormat:@"MM-dd HH:mm"];
            chatTimeStr = [df stringFromDate:beDate];
        }
    } else if ([self isSameWeekWithDate:[NSDate dateWithTimeIntervalSince1970:timeStamp]]) {
        // 周几
        NSString *weekStr = [self weekDayStr:timeStamp];
        chatTimeStr = [NSString stringWithFormat:@"%@ %@",weekStr,[self showTimeFormat:@"HH:mm" interval:timeStamp]];
    } else {
        chatTimeStr = [self showTimeFormat:@"YYYY-MM-dd HH:mm:ss"
                                  interval:timeStamp];
    }
    
    return chatTimeStr;
}

// 根据某个格式显示时间
+ (NSString *)showTimeFormat:(NSString *)format
                    interval:(int64_t)interval {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    return [formatter stringFromDate:date];
}

/**
 根据时间戳计算周几
 
 @param timeStamp 时间戳
 @return 周几
 */
+ (NSString *)weekDayStr:(int64_t)timeStamp {
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents*comps = [[NSDateComponents alloc]init];
    NSInteger unitFlags = NSCalendarUnitWeekday;
    
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
    comps = [calendar components:unitFlags fromDate:date];
    NSInteger iDay = [comps weekday];

    NSString *retStr = @"";
    switch (iDay) {
        case 1:
            retStr = @"周日";
            break;
        case 2:
            retStr = @"周一";
            break;
        case 3:
            retStr = @"周二";
            break;
        case 4:
            retStr = @"周三";
            break;
        case 5:
            retStr = @"周四";
            break;
        case 6:
            retStr = @"周五";
            break;
        case 7:
            retStr = @"周六";
            break;
        default:
            break;
    }
    return retStr;
}

/**
 获取当前时间
 
 @return 当前时间
 */
+ (NSString *)currentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSDate *date = [NSDate date];
    return [formatter stringFromDate:date];
}

/**
 NSData类型转换成十六进制字符串
 
 @param data nsdata数据
 @return 十六进制字符串
 */
+ (NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] ==0) {
        return @"";
    }
    
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    [data enumerateByteRangesUsingBlock:^(const void * _Nonnull bytes, NSRange byteRange, BOOL * _Nonnull stop) {
        unsigned char *dateBytes = (unsigned char *)bytes;
        for (NSUInteger i = 0; i<byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x",(dateBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@",hexStr];
            }
        }
    }];
    
    return string;
}

/**
 十六进制转成NSData
 
 @param hexString 十六进制字符串
 @return NSData类型
 */
+ (NSData*)dataFormHexString:(NSString*)hexString{
    hexString=[[hexString uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (!(hexString && [hexString length] > 0 && [hexString length]%2 == 0)) {
        return nil;
    }
    Byte tempbyt[1]={0};
    NSMutableData* bytes=[NSMutableData data];
    for(int i=0;i<[hexString length];i++)
    {
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else
            return nil;
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char2 >= 'A' && hex_char2 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else
            return nil;
        
        tempbyt[0] = int_ch1+int_ch2;  ///将转化后的数放入Byte数组里
        [bytes appendBytes:tempbyt length:1];
    }
    return bytes;
}

/**
 取指定路径下文件数据

 @param fileFullPath 文件路径
 @return NSData类型
 */
+ (NSData *)dataFromPath:(NSString *)fileFullPath {
    NSData *tempData = [[NSData alloc] initWithContentsOfFile:fileFullPath];
    return tempData;
}

/**
 统计字符串出现次数

 @param str 被统计的字符串
 @param subStr 统计字符串
 @return 次数
 */
+ (NSUInteger)cauculateTimer:(NSString *)str
                      subStr:(NSString *)subStr{
    NSUInteger cnt = 0;
    NSUInteger length = [str length];
    NSRange range = NSMakeRange(0, length);
    while(range.location != NSNotFound)
    {
        range = [str rangeOfString: subStr options:0 range:range];
        if(range.location != NSNotFound)
        {
            range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
            cnt++;
        }
    }
    
    return cnt;
}



+ (ImMessage *)createMessage:(NSString *)protocol
                     version:(NSString *)version
                      userId:(NSString *)userId
                   userToken:(NSString *)userToken
                   messageId:(UInt32)messageId
                 messageType:(NSString *)messageType
                 messageTime:(UInt64)messageTime
                    termType:(NSString *)termType
                    receiver:(NSString *)receiver
                      sender:(NSString *)sender
               ctrlMessageId:(UInt32)ctrlMessageId
                   mediaType:(NSString *)mediaType
                    playload:(NSData *)playload {
    
    
    ImMessage *_mess = [ImMessage new];
    _mess.protocol = protocol;
    _mess.version = version;
    _mess.userId = userId;
    _mess.userToken = userToken;
    _mess.messageId = messageId;
    _mess.messageType = messageType;
    _mess.messageTime = messageTime;
    _mess.termType = termType;
    _mess.receiver = receiver;
    _mess.sender = sender;
    _mess.ctrlMessageId = ctrlMessageId;
    _mess.mediaType = mediaType;
    _mess.payload = playload;
    
    return _mess;
}

+ (ImMessage *)createMessage:(NSString *)protocol
                     version:(NSString *)version
                      userId:(NSString *)userId
                   userToken:(NSString *)userToken
                   messageId:(UInt32)messageId
                 messageType:(NSString *)messageType
                 messageTime:(UInt64)messageTime
                    termType:(NSString *)termType
                    receiver:(NSString *)receiver
                      sender:(NSString *)sender
               ctrlMessageId:(UInt32)ctrlMessageId
                   mediaType:(NSString *)mediaType
                    playload:(NSData *)playload
                      avatar:(NSString *)avatar
{
    
    
    ImMessage *_mess = [ImMessage new];
    _mess.protocol = protocol;
    _mess.version = version;
    _mess.userId = userId;
    _mess.userToken = userToken;
    _mess.messageId = messageId;
    _mess.messageType = messageType;
    _mess.messageTime = messageTime;
    _mess.termType = termType;
    _mess.receiver = receiver;
    _mess.sender = sender;
    _mess.ctrlMessageId = ctrlMessageId;
    _mess.mediaType = mediaType;
    _mess.payload = playload;
    _mess.avatar = avatar;
    
    return _mess;
}

+ (ImMessage *)createMessage:(NSString *)protocol
                     version:(NSString *)version
                      userId:(NSString *)userId
                   userToken:(NSString *)userToken
                   messageId:(UInt32)messageId
                 messageType:(NSString *)messageType
                 messageTime:(UInt64)messageTime
                    termType:(NSString *)termType
                    receiver:(NSString *)receiver
                      sender:(NSString *)sender
               ctrlMessageId:(UInt32)ctrlMessageId
                    playload:(NSData *)playload {
    
    
    ImMessage *_mess = [ImMessage new];
    _mess.protocol = protocol;
    _mess.version = version;
    _mess.userId = userId;
    _mess.userToken = userToken;
    _mess.messageId = messageId;
    _mess.messageType = messageType;
    _mess.messageTime = messageTime;
    _mess.termType = termType;
    _mess.receiver = receiver;
    _mess.sender = sender;
    _mess.ctrlMessageId = ctrlMessageId;
    _mess.payload = playload;
    
    return _mess;
}

/**
 判断跟当前日期是否在同一周
 
 @param date 时间
 @return 是否同一周
 */
+ (BOOL) isSameWeekWithDate:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    int unit = NSCalendarUnitWeekday | NSCalendarUnitMonth | NSCalendarUnitYear | kCFCalendarUnitDay | kCFCalendarUnitHour | kCFCalendarUnitMinute ;
    //1.获得当前时间的 年月日
    NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]]; NSDateComponents *sourceCmps = [calendar components:unit fromDate:date];
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:[NSDate date] toDate:date options:0];
    NSInteger subDay = labs(dateCom.day);
    NSInteger subMonth = labs(dateCom.month);
    NSInteger subYear = labs(dateCom.year);
    if (subYear == 0 && subMonth == 0) {
        //当相关的差值等于零的时候说明在一个年、月、日的时间范围内，不是按照零点到零点的时间算的
        if (subDay > 6) { //相差天数大于6肯定不在一周内
            return NO;
        }
        else { //相差的天数大于或等于后面的时间所对应的weekday则不在一周内
            if (dateCom.day >= 0 && dateCom.hour >=0 && dateCom.minute >= 0) {
                //比较的时间大于当前时间
                //西方一周的开始是从周日开始算的，周日是1，周一是2，而我们是从周一开始算新的一周
                NSInteger chinaWeekday = sourceCmps.weekday == 1 ? 7 : sourceCmps.weekday - 1;
                if (subDay >= chinaWeekday){
                    return NO;
                }
                else {
                    return YES;
                }
                
            } else {
                NSInteger chinaWeekday = sourceCmps.weekday == 1 ? 7 : nowCmps.weekday - 1;
                if (subDay >= chinaWeekday) {
                    //比较的时间比当前时间小，已经过去的时间
                    return NO;
                } else {
                    return YES;
                }
            }
        }
    }
    else { //时间范围差值超过了一年或一个月的时间范围肯定就不在一个周内了
        return NO;
    }
}


@end
